package cn.tomoya.module.security.core;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.tomoya.common.config.SiteConfig;
import cn.tomoya.module.security.JwtTokenUtil;
import cn.tomoya.module.security.entity.Permission;
import cn.tomoya.module.security.service.PermissionService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;

@Service
public class MyUserDetailService implements UserDetailsService {

    Logger log = Logger.getLogger(MyUserDetailService.class);

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private SiteConfig siteConfig;

//    public UserDetails loadUserByUsernameByToken(String username) {
//        User user = new User();
//        String tokenUserName = jwtTokenUtil.getUsernameFromToken(username);
//        if(StringUtils.isEmpty(tokenUserName)){
//            user = userService.findByUsername("ddd");
//        }else{
//            String name = "sso_"+siteConfig.getJwtSecret();
//            user = userService.findByUsername(name);
//        }
//        if (user != null) {
//            List<Permission> permissions = permissionService.findByAdminUserId(user.getId());
//            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//            for (Permission permission : permissions) {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
//                grantedAuthorities.add(grantedAuthority);
//            }
//            UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
//            if(!StringUtils.isEmpty(tokenUserName)){
//                user.
//                user.setUsername(tokenUserName);
//            }
//            return userDetails;
//        } else {
//            log.info("用户" + username + " 不存在");
//            throw new UsernameNotFoundException("用户名或密码不正确");
//        }
//    }

    public UserDetails loadUserByUsername(String username) {

        HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        /*String imagecodeText = request.getParameter("imagecodeText");
        String piccode = (String) request.getSession().getAttribute("piccode");*/
        User user = userService.findByUsername(username);
        /*if (!StringUtils.isEmpty(imagecodeText)){
            if (piccode.equals(imagecodeText)) {*/
//                User user = userService.findByUsername(username);
                if (user != null) {
                    List<Permission> permissions = permissionService.findByAdminUserId(user.getId());

                    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                    for (Permission permission : permissions) {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
//                        new SimpleGrantedAuthority(user.getRoles().toString());
                       /* Iterator<Role> iterators = user.getRoles().iterator();

                        while (iterators.hasNext()){
                            GrantedAuthority grantedAuthorityRole = new SimpleGrantedAuthority(iterators.next().getName());
                            System.out.println(iterators.next().getName()+"++++++++++++++++++++++++++++++++++++++++++");
                            grantedAuthorities.add(grantedAuthorityRole);
                        }*/
                        grantedAuthorities.add(grantedAuthority);
                    }
                    UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
                    return userDetails;
                } else {
                    log.info("用户" + username + " 不存在");
//                    request.setAttribute("message","用户名或密码不正确!");
                    throw new UsernameNotFoundException("username not creae");

                }
            /*}else {
//                request.setAttribute("message","验证码不正确!");
                throw new UsernameNotFoundException("code not ");
            }*/
        /*}else{*/
//          /*  request.setAttribute("message","验证码不能为空!");
//            throw new UsernameNotFoundException("code not empty!");
           /* if (user != null) {
                List<Permission> permissions = permissionService.findByAdminUserId(user.getId());
                List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                for (Permission permission : permissions) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
                    grantedAuthorities.add(grantedAuthority);
                }
                UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
                return userDetails;
            } else {
                log.info("用户" + username + " 不存在");
                throw new UsernameNotFoundException("用户名或密码不正确");
            }*/
         /*   throw new UsernameNotFoundException("验证码为空");
        }*/

        /*User user = userService.findByUsername(username);
        if (user != null) {
            List<Permission> permissions = permissionService.findByAdminUserId(user.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (Permission permission : permissions) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
                grantedAuthorities.add(grantedAuthority);
            }
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
            return userDetails;
        } else {
            log.info("用户" + username + " 不存在");
            throw new UsernameNotFoundException("用户名或密码不正确");
        }*/
    }

}
